package workerpool

import (
	"context"
	"fmt"
	"regexp"
	"sync"
	"taskschedu/task"
	"time"

	consulapi "github.com/hashicorp/consul/api"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

var (
	workerNodes      []string
	currentNodeIndex int
	mu               sync.Mutex
	stopChan         chan struct{}
)

// var workerNodes = []string{"worker:50051"}
// var currentNodeIndex = 0
// var mu sync.Mutex

// func GetNextNode() string {
// 	mu.Lock()
// 	defer mu.Unlock()
// 	currentNodeIndex = (currentNodeIndex + 1) % len(workerNodes)
// 	return workerNodes[currentNodeIndex]
// }

// StartWorkerDiscovery 开始worker节点发现
func StartWorkerDiscovery(servicePattern string) error {
	stopChan = make(chan struct{})
	go discoverWorkers(servicePattern)
	return nil
}

// StopWorkerDiscovery 停止worker节点发现
func StopWorkerDiscovery() {
	if stopChan != nil {
		close(stopChan)
	}
}

// discoverWorkers 定期从Consul发现worker节点
func discoverWorkers(servicePattern string) {
	ticker := time.NewTicker(10 * time.Second)
	defer ticker.Stop()

	for {
		select {
		case <-stopChan:
			return
		case <-ticker.C:
			updateWorkerNodes(servicePattern)
		}
	}
}

// updateWorkerNodes 更新worker节点列表
func updateWorkerNodes(servicePattern string) {
	config := consulapi.DefaultConfig()
	config.Address = "172.31.6.101:8500"
	consulClient, err := consulapi.NewClient(config)
	if err != nil {
		fmt.Printf("创建 consul 客户端失败: %v\n", err)
		return
	}

	// 获取所有服务
	services, err := consulClient.Agent().Services()
	if err != nil {
		fmt.Printf("获取服务列表失败: %v\n", err)
		return
	}

	// 编译正则表达式
	pattern, err := regexp.Compile(servicePattern)
	if err != nil {
		fmt.Printf("正则表达式编译失败: %v\n", err)
		return
	}

	// 查找匹配的服务
	var newNodes []string
	for id, service := range services {
		if pattern.MatchString(id) {
			// 构建gRPC连接地址
			nodeAddr := fmt.Sprintf("%s:%d", service.Address, service.Port)
			newNodes = append(newNodes, nodeAddr)
		}
	}

	// 更新worker节点列表
	mu.Lock()
	workerNodes = newNodes
	if currentNodeIndex >= len(workerNodes) {
		currentNodeIndex = 0
	}
	mu.Unlock()

	fmt.Printf("更新worker节点列表: %v\n", newNodes)
}

// GetNextNode 获取下一个可用的worker节点
func GetNextNode() string {
	mu.Lock()
	defer mu.Unlock()
	if len(workerNodes) == 0 {
		return ""
	}
	currentNodeIndex = (currentNodeIndex + 1) % len(workerNodes)
	return workerNodes[currentNodeIndex]
}

func DispatchTaskToWorker(taskID string, command string) (string, error) {
	node := GetNextNode()
	if node == "" {
		return "", fmt.Errorf("没有可用的worker节点")
	}

	conn, err := grpc.NewClient(node, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		return "", fmt.Errorf("连接worker失败: %v", err)
	}
	defer conn.Close()

	client := task.NewWorkerClient(conn)
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
	defer cancel()

	response, err := client.ExecuteTask(ctx, &task.TaskRequest{
		TaskId:  taskID,
		Command: command,
	})
	if err != nil {
		return "", fmt.Errorf("执行任务失败: %v", err)
	}
	return response.Result, nil
}
